from django.shortcuts import render
from django.http import HttpResponse, JsonResponse

from .. import models
from django.core.urlresolvers import reverse
from . import viewsIndex

# 商品列表
def goodsindex(request):
    # 查询
    data = models.Goods.objects.filter().exclude(status=3)

     # 获取请求参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否右搜索条件
    if types:
        if types == 'title':
            # 按标题搜索
            data = data.filter(title__contains=keywords)
        elif types == 'price':
      
            # 获取价格区间
            arr = keywords.split(',')
            data = data.filter(price__gte=arr[0]).filter(price__lte=arr[1])

        elif types == 'status':
            # 按状态搜索
            if keywords == "新品":
                data = data.filter(status=0)
            elif keywords == "热卖":
                data = data.filter(status=1)
            elif keywords == "下架":
                data = data.filter(status=2)
            elif keywords == "删除":
                data = models.Goods.objects.filter(status=3)

    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页类
    paginator = Paginator(data,10)

    # 获取当前页码
    p = int(request.GET.get('p',1))

    # 获取分页数据对象[{id:1},{id:2}]  [{id:3},{id:4}]
    goodslist = paginator.page(p)

    # 分配数据
    context = {'goodslist': goodslist}
    return render(request, 'myadmin/goods/index.html', context)

# 商品添加
def goodsadd(request):
    # 获取所有的商品分类
    data = models.Cates.objects.extra(select = {'paths':'concat(path, id)'}).order_by('paths')
    # 分配数据
    context = {'cateslist':data}
    # 加载模板
    return render(request,'myadmin/goods/add.html',context)

# 执行商品添加
def goodsinsert(request):
    try:
        # 接受数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        data['cateid'] = models.Cates.objects.get(id=data['cateid'])

        # 处理上传的商品主图
        myfile = request.FILES.get('pic_url')
        if myfile:
            data['pic_url'] = viewsIndex.uploads(myfile)
        else:
            return HttpResponse('<script>alert("必须上传商品主图");history.back(-1);</script>')

        # 执行数据的添加
        ob = models.Goods(**data)
        ob.save()
        return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_goods_add')+'"</script>')

# 商品删除
def goodsdel(request, gid):
    try:
        # 根据uid获取商品对象，修改状态
        ob = models.Goods.objects.get(id=gid)
        # ob.status = 3
        # ob.save()
        ob.delete()

        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_goods_index')+'"</script>')

# 商品修改
def goodsedit(request):
    # 获取传递的商品id
    gid = request.GET.get('gid')
    # 获取商品数据对象
    ob = models.Goods.objects.get(id=gid)

    if request.method =='GET':
        # 获取所有的商品分类数据
        cateslist = models.Cates.objects.extra(select = {'paths':'concat(path, id)'}).order_by('paths')
        # 分配数据
        context = {'ginfo':ob, 'cateslist': cateslist}
        # 加载模板
        return render(request,'myadmin/goods/edit.html',context)
    else:
        # try:
            # 执行更新
            data = request.POST.dict()
            data.pop('csrfmiddlewaretoken')

            # 修改对象的数据
            ob.cateid = models.Cates.objects.get(id=data['cateid'])
            # 判断是否上传了新的图片
            myfile = request.FILES.get('pic_url')
            if myfile:
                # 删除旧图
                # os.remove(BASE_DIR+ob.pic_url)
                # 上传新的图片,更新数据
                ob.pic_url = uploads(myfile)
            ob.title = data['title']
            ob.price = data['price']
            ob.store = data['store']
            ob.info = data['info']
            ob.save()
            return HttpResponse('<script>alert("更新成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')